const mongoose = require('mongoose');
const Classify = require('../models/classify.model');

exports.create = function(req, res, next) {
    var classify = new Classify(req.body);
    console.log(req.body);
    classify.save().then(data => {
        res.json(data);
    })
}

exports.update = function(req, res, next) {
    const id = req.params.id;
    // console.log(id);

    Classify.findByIdAndUpdate(id, { $set: req.body }).then(data => {
        res.json(data);
    });
}

// exports.remove = function(req, res, next) {
//     const id = req.params.id;

//     Classify.findByIdAndRemove(id, function(err, data) {
//         res.json(data);
//     });
// }
exports.remove = function(req, res, next) {
    var ids = req.params.id;
    ids = ids.split(',');
    Classify.remove({ _id: { $in: ids } }, function(data) {
        res.json(data);
    });
};


exports.list = function(req, res, next) {

    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 5;
    var queryCondition = {};
    var cateId = req.body.cateId;
    if (cateId === undefined) {
        res.json({ message: 'error message' });
        return;
    } else {
        cateId = req.body.cateId;
        queryCondition = {
            cateId: cateId
        }
    }

    if (req.body.title && req.body.title.trim().length > 0) {
        title = req.body.title;
        queryCondition = Object.assign(queryCondition, {
            "title": new RegExp(title, 'i')
        })
    }
    console.log(queryCondition);


    Classify.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}
exports.get = function(req, res, next) {
    const id = req.params.id;
    Classify.findById(id).then(data => {
        res.json(data);
    })
}